package plugin.redis;

import play.Play;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author zqx
 * @date 16/3/3
 */
class RedisDataSource {

    private static JedisPool jedisPool = null;

    /*
     * 初始化Redis连接池
     */
    static {
        if ("on".equals(Play.configuration.getProperty("redis.switch"))) {
            try {
                boolean debug = Boolean.parseBoolean(Play.configuration.getProperty("redis.debug"));
                String host = Play.configuration.getProperty("redis.host");
                int port = Integer.parseInt(Play.configuration.getProperty("redis.port"));
                if (debug) {
                    host = Play.configuration.getProperty("redis.debug.host");
                    port = Integer.parseInt(Play.configuration.getProperty("redis.debug.port"));
                }
                int maxActive = Integer.parseInt(Play.configuration.getProperty("redis.pool.maxActive"));
                int maxWait = Integer.parseInt(Play.configuration.getProperty("redis.pool.maxWait"));
                int maxIdel = Integer.parseInt(Play.configuration.getProperty("redis.pool.maxIdle"));
                int timeout = Integer.parseInt(Play.configuration.getProperty("redis.pool.timeout"));
                int dbIndex = Integer.parseInt(Play.configuration.getProperty("redis.pool.db.index"));

                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxActive(maxActive);
                config.setMaxIdle(maxIdel);
                config.setMaxWait(maxWait);
                config.setTestOnBorrow(true);
                jedisPool = new JedisPool(config, host, port, timeout, null, dbIndex);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void release(Jedis jedis) {
        jedisPool.returnResource(jedis);
    }

    public static Jedis getJedis() {
        return jedisPool.getResource();
    }
}